//
//  ICMSelecteStepInTimeView.m
//  ICrEAM
//
//  Created by rainimute on 16/11/2.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMSelecteStepInTimeView.h"
#import "ICMSelecteStepInTimeCell.h"
#import "ICMTimeBarView.h"
#import "ICMDatePickerView.h"
#import "NSDate+convenience.h"
#import "ICMSelecteItemDataView.h"
#import "PACACalendarView.h"
#import "ICMAppointmentBasicInfoView.h"

@interface ICMSelecteStepInTimeView ()<UITableViewDelegate,UITableViewDataSource,ICMSelecteStepInTimeCellDelegate,UIScrollViewDelegate,ICMDatePickerViewDelegate,ICMSelecteItemDataViewDelegate,PACACalendarViewDelegate>

@property (nonatomic, strong) UIScrollView *bigScrollView;

@property (nonatomic, assign) float itemWidth;

@property (nonatomic, strong) NSDate *selectedDate;

@property (nonatomic, copy) NSString *selectedStationIndex;

@property (nonatomic, copy) ICMSelecteItemDataView *itemDataView;

@property (nonatomic, copy) NSString *stationBeginTime;            //进站时间
@property (nonatomic, copy) NSString *stationTime;                 //可预约时间

@property (nonatomic, assign) float SKServerEmptyTime;             //可用时间

@property (nonatomic, strong) NSMutableArray *currentSelectedTimes;//创建时就有的选中时间



@end

@implementation ICMSelecteStepInTimeView

#pragma mark    初始化
- (instancetype)initWithFrame:(CGRect)frame andServer:(NSString*)serverCode andAppointmentDate:(NSString*)appointmentDate andReceptionTime:(NSString *)receptionTime andStationBeginTime:(NSString*)stationBeginTime andStationTime:(NSString*)stationTime andStationCode:(NSString*)stationCode andBackTarge:(UIView*)targe{
    if (self = [super initWithFrame:frame]) {
        ICMAppointmentBasicInfoView *targeView = (ICMAppointmentBasicInfoView *)targe;
        self.delegate = targeView.delegate;
        self.stationBeginTime = stationBeginTime;
        self.stationTime = stationTime;
        self.stationCode = stationCode;
        
        self.backgroundColor = [UIColor whiteColor];
        BorderColor(self, 0x000000);
        BorderWidth(self, 1);
        CornerRadius(self, 4);
        //
        self.serverTimeModel = [[ICMSelecteTimeModel alloc]init];
        
        self.stationModels = [NSMutableArray array];
        
        //
        
        self.serviceAdvisorView = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(ActualWidth(100), ActualHeight(50), ActualWidth(125), ActualHeight(63)) title:@"预约服务顾问" addTarget:self selector:@selector(serviceAdvisorViewAction)];
        
        
        self.serviceAdvisorView.contentText = [ICrEAMUser shareICrEAMUser].user_name;
        [self addSubview:self.serviceAdvisorView];
        //
        self.stepInTimeView = [ICMTitleTextFeildView createClickableICMTitleTextFeildViewWithFrame:CGRectMake(self.serviceAdvisorView.rightEdge+ActualWidth(50), CGRectGetMinY(self.serviceAdvisorView.frame), ActualWidth(125), ActualHeight(63)) title:@"预约进站时间" addTarget:self selector:@selector(clickCalenderBtn)];
        
    
        self.stepInTimeView.contentText =(appointmentDate&&![appointmentDate isEqualToString:@""])?[appointmentDate componentsSeparatedByString:@" "].firstObject:[self dateStr];
        
        
        NSArray *stepInTimeArray = [self.stepInTimeView.contentText componentsSeparatedByString:@"-"];
        self.selectedDate = [ICrEAMTool getDateWithDateDesc:[NSString stringWithFormat:@"%@-%@-%@ 00:00",stepInTimeArray[2],stepInTimeArray[1],stepInTimeArray[0]]];
        [self addSubview:self.stepInTimeView];
        //
        UIButton *calenderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        calenderBtn.frame = CGRectMake(self.stepInTimeView.rightEdge, self.stepInTimeView.bottomEdge-ActualWidth(35), ActualWidth(35), ActualWidth(35));
        [calenderBtn setUpButtonWithNormolTitle:nil selectedTitle:nil normolTitleSize:0 selectedTitleSize:0 normolTitleColor:nil selectedTitleColor:nil normolBcakImage:[UIImage imageNamed:Appointment_Calendar] selectedBackImage:nil actionSEL:@selector(clickCalenderBtn) target:self];
        [self addSubview:calenderBtn];
        //计算itemWidth
        float scrollViewWidth = (CGRectGetWidth(frame)-CGRectGetMinX(self.serviceAdvisorView.frame)-ActualWidth(40));
        float itemWidth = scrollViewWidth/24;
        self.itemWidth = itemWidth;
        //预约进站时间tableView
        self.bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.serviceAdvisorView.frame), self.serviceAdvisorView.bottomEdge+ActualHeight(45), scrollViewWidth, CGRectGetHeight(frame)-self.serviceAdvisorView.bottomEdge-60)];
        self.bigScrollView.backgroundColor = [UIColor clearColor];
        self.bigScrollView.layer.masksToBounds = NO;
        self.bigScrollView.clipsToBounds = NO;
        //需要加上时间条
        ICMTimeBarView *timeBarViewUp = [ICMTimeBarView createTimeBarViewWithFrame:CGRectMake(-itemWidth, 0, itemWidth*54, 30) andItemWidth:itemWidth];
        [self.bigScrollView addSubview:timeBarViewUp];
        //添加之前的预约记录
        if (receptionTime && ![receptionTime isEqualToString:@""]) {
            NSInteger count = [receptionTime floatValue]/0.25;
            NSInteger minCount = [self hourAndMinTextGetCount:[[appointmentDate componentsSeparatedByString:@" "]lastObject]];
            self.currentSelectedTimes = [NSMutableArray array];
            for (NSInteger i=0; i<count; i++) {
                [self.currentSelectedTimes addObject:[@(minCount+i) stringValue]];
            }
            if (![ICrEAMTool isVW]) {
                self.serviceAdvisorView.contentTextButton.userInteractionEnabled = NO;
                self.stepInTimeView.contentTextButton.userInteractionEnabled = NO;
            }
        }
        //
        self.stepInTimeTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, timeBarViewUp.bottomEdge, itemWidth*52, itemWidth)];
        self.stepInTimeTableView.scrollEnabled = NO;
        [self.stepInTimeTableView registerClass:[ICMSelecteStepInTimeCell class] forCellReuseIdentifier:@"ICMSelecteStepInTimeCell"];
        self.stepInTimeTableView.delegate = self;
        self.stepInTimeTableView.dataSource = self;
        [self.bigScrollView addSubview:self.stepInTimeTableView];
        //
        UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake(0, self.stepInTimeTableView.bottomEdge+20+self.bigScrollView.y, CGRectGetWidth(frame), 2)];
        sepView.backgroundColor = SepColor_gray;
        [self addSubview:sepView];
        //
        UILabel *stationLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.serviceAdvisorView.x, sepView.bottomEdge+20, 200, 30)];
        [stationLabel setUpLabelWithText:@"预约工位" alignment:NSTextAlignmentLeft textSize:TitleSize textColor:TitleColor_Dark];
        [self addSubview:stationLabel];
        
        //预约工位tableView
        ICMTimeBarView *timeBarViewDown = [ICMTimeBarView createTimeBarViewWithFrame:CGRectMake(-itemWidth, stationLabel.bottomEdge-self.bigScrollView.y, itemWidth*54, 30) andItemWidth:itemWidth];
        [self.bigScrollView addSubview:timeBarViewDown];
        self.stationTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, timeBarViewDown.bottomEdge, itemWidth*52, CGRectGetHeight(self.bigScrollView.frame)-stationLabel.bottomEdge-10-30+self.bigScrollView.y)];
        [self.stationTableView registerClass:[ICMSelecteStepInTimeCell class] forCellReuseIdentifier:@"ICMSelecteStepInTimeCell"];
        self.stationTableView.delegate = self;
        self.stationTableView.dataSource = self;
        self.stationTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        self.stationTableView.tableFooterView.backgroundColor = Color(0xE4E4E2);
        [self.bigScrollView addSubview:self.stationTableView];
        
        self.bigScrollView.contentSize = CGSizeMake(itemWidth*52, CGRectGetHeight(frame)-self.serviceAdvisorView.bottomEdge-60);
        [self addSubview:self.bigScrollView];
        
        //工位名称列表
        self.stationTitleTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.stationTableView.y+self.bigScrollView.y, self.bigScrollView.x, CGRectGetHeight(self.stationTableView.frame))];
        self.stationTitleTableView.scrollEnabled=NO;
        self.stationTitleTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.stationTitleTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"stationTitleTableViewCell"];
        self.stationTitleTableView.delegate = self;
        self.stationTitleTableView.dataSource = self;
        [self addSubview:self.stationTitleTableView];
        
        ICrEAMUser *user = [ICrEAMUser shareICrEAMUser];
        
        self.userId = (serverCode&&![serverCode isEqualToString:@""])?serverCode:user.employee_NO;
        [self getTimeDataWithDate:(appointmentDate&&![appointmentDate isEqualToString:@""])?[appointmentDate componentsSeparatedByString:@" "].firstObject:[self dateStr] andUserId:self.userId];
        
        [self getAllServerNameAndCode];
        
        //挡住时间块和时间条
        UIView *maskView1 = [[UIView alloc]initWithFrame:CGRectMake(0, self.bigScrollView.y, self.bigScrollView.x-itemWidth/2, timeBarViewUp.height)];
        maskView1.backgroundColor = [UIColor whiteColor];
        [self addSubview:maskView1];
        UIView *maskView2 = [[UIView alloc]initWithFrame:CGRectMake(0, self.bigScrollView.y+self.stepInTimeTableView.y, self.bigScrollView.x, itemWidth)];
        maskView2.backgroundColor = [UIColor whiteColor];
        [self addSubview:maskView2];
        UIView *maskView3 = [[UIView alloc]initWithFrame:CGRectMake(0, timeBarViewDown.y+self.bigScrollView.y, maskView1.width, maskView1.height)];
        maskView3.backgroundColor = [UIColor whiteColor];
        [self addSubview:maskView3];
        UIView *maskView4 = [[UIView alloc]initWithFrame:CGRectMake(self.bigScrollView.rightEdge, maskView2.y, ActualWidth(40), maskView2.height)];
        maskView4.backgroundColor = [UIColor whiteColor];
        [self addSubview:maskView4];
        UIView *maskView5 = [[UIView alloc]initWithFrame:CGRectMake(self.bigScrollView.rightEdge, self.stationTitleTableView.y, ActualWidth(40), self.stationTitleTableView.height)];
        maskView5.backgroundColor = [UIColor whiteColor];
        [self addSubview:maskView5];
        
        //关闭按钮
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(self.width-80, 0, 80, 80)];
        [backButton setUpButtonWithNormolTitle:nil selectedTitle:nil normolTitleSize:0 selectedTitleSize:0 normolTitleColor:nil selectedTitleColor:nil normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(stepInTimeViewBackButtonAction:) target:targe];
        UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake(52, 10, 18, 18)];
        backImage.image = [UIImage imageNamed:@"btn_tableview_delete"];
        [backButton addSubview:backImage];
        [self addSubview:backButton];
    }
    return self;
}
#pragma mark    覆盖当前时间不能选择的时间格
- (void)markPassOverOfToday{
    if (![self.stepInTimeView.contentText isEqualToString:[ICrEAMTool getNowDate]]&&[ICrEAMTool isVW]) {
        [self.stationTableView reloadData];
        [self.stepInTimeTableView reloadData];
        [self.stationTitleTableView reloadData];
        return;
    }
    for (NSInteger i=0; i<self.currentMinIndex; i++) {
        [self.serverTimeModel.haveSelectedTimes addObject:[@(i) stringValue]];
        for (ICMSelecteTimeModel *timeModel in self.stationModels) {
            [timeModel.haveSelectedTimes addObject:[@(i) stringValue]];
        }
        if ([self.serverTimeModel.currentSelectedTimes containsObject:[@(i) stringValue]]) {
            [self.serverTimeModel.currentSelectedTimes removeObject:[@(i) stringValue]];
        }
    }
    [self.stationTableView reloadData];
    [self.stepInTimeTableView reloadData];
    [self.stationTitleTableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return tableView == self.stepInTimeTableView ? 1:self.stationModels.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.stationTitleTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"stationTitleTableViewCell"];
        ICMSelecteTimeModel *selecteTimeModel = [self.stationModels objectAtIndex:indexPath.row];
        
        cell.textLabel.textAlignment = NSTextAlignmentRight;
        [cell.textLabel setUpLabelWithText:selecteTimeModel.itemTitle alignment:NSTextAlignmentRight textSize:14 textColor:[UIColor grayColor]];
        [cell.textLabel changeXToOtherX:0];
        [cell.textLabel changeWidthToOtherWidth:self.bigScrollView.x];
        return cell;
    }
    ICMSelecteStepInTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICMSelecteStepInTimeCell"];
    cell.delegate = self;
    NSArray *didSelectedTimes;
    NSMutableArray *onlineSourceTimes;
    NSMutableArray *currentSelectedTimes;
    if (tableView == self.stepInTimeTableView) {
        didSelectedTimes = self.serverTimeModel.haveSelectedTimes;
        currentSelectedTimes = self.serverTimeModel.currentSelectedTimes;
    }else{
        ICMSelecteTimeModel *selecteTimeModel = [self.stationModels objectAtIndex:indexPath.row];
        didSelectedTimes = selecteTimeModel.haveSelectedTimes;
        onlineSourceTimes = selecteTimeModel.onlineSourceTimes;
        currentSelectedTimes = selecteTimeModel.currentSelectedTimes;
    }

    [cell setupSelecteStepInTimeCellWithDidSelectedTimes:didSelectedTimes andCurrentSelectedTimes:currentSelectedTimes andOnlineSource:onlineSourceTimes andItemWidth:self.itemWidth];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.itemWidth;
}

                            /*button点击事件*/
#pragma mark    服务顾问选择框点击
- (void)serviceAdvisorViewAction{
    _itemDataView = [ICMSelecteItemDataView createSelecteItemDataViewWithSourceView:self.serviceAdvisorView andItemDatas:self.serviceAdvisorView.clickDataArray frame:self.frame];
    _itemDataView.delegate = self;
    [self addSubview:_itemDataView];
}
#pragma mark    点击日历
- (void)clickCalenderBtn{
//    [NSDate dateWithTimeIntervalSinceNow:60*24*60*60]
    PACACalendarView *calendarView = [PACACalendarView createCalendarViewWithDidSelectedDate:self.selectedDate minDate:[NSDate date] maxDate:nil andFrame:CGRectMake(ScreenWidth/2-150, ScreenHeight/2-150, ActualWidth(300), ActualWidth(380))];
    calendarView.delegate = self;
    [Window addSubview:calendarView];
}

/*ICMSelecteStepInTimeCellDelegate*/
#pragma mark    点击时间格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath andButtonIndex:(NSInteger)buttonIndex{
    ICMSelecteTimeModel *selecteTimeModel;
    if ([self.stepInTimeView.contentText isEqualToString:[self dateStr]]) {
        if (buttonIndex+1 < self.currentMinIndex) {
            [self showString:@"预约不能选择过去时间!" forSeconds:1.5];
            return;
        }
    }
    if (tableView == self.stepInTimeTableView) {
        if (![ICrEAMTool isVW]) {
            if (self.isEditType) {
                return;
            }
//            if (buttonIndex == 51) {
//                [self showString:@"服务顾问服务时间不能少于30分钟!" forSeconds:1.5];
//                return;
//            }
        }else{
            if (self.isOnline && self.selectedStationIndex) {
                ICMSelecteTimeModel *didSelecteTimeModel = [self.stationModels objectAtIndex:[self.selectedStationIndex integerValue]];
                if (buttonIndex>(didSelecteTimeModel.lastServerIndex-didSelecteTimeModel.currentSelectedTimes.count)) {
                    [self showString:@"工位预约时间必须晚于服务顾问预约结束时间！" forSeconds:1.5];
                    return;
                }
            }
        }
        if (self.serverTimeModel.currentSelectedTimes.count == 2 && ![self.serverTimeModel.currentSelectedTimes containsObject:[@(buttonIndex)stringValue]]) {
            [self showString:@"服务顾问只能预约两格,请先取消已选的时间!" forSeconds:1.5];
            return;
        }
        selecteTimeModel = self.serverTimeModel;
        if (self.selectedStationIndex) {
            ICMSelecteTimeModel *didSelecteTimeModel = [self.stationModels objectAtIndex:[self.selectedStationIndex integerValue]];
            if (!(self.isOnline && [ICrEAMTool isVW])) {
                [didSelecteTimeModel.currentSelectedTimes removeAllObjects];
            }
            dispatch_main_async_safe(^{
                [self.stationTableView reloadData];
            });
        }
        
    }else{
        //VW含有在线资源不能编辑工位信息
        if ([ICrEAMTool isVW] && self.isOnline) {
            return;
        }
        //还没有预约选择服务顾问时间----斯柯达
        if (self.serverTimeModel.currentSelectedTimes.count < 2 && ![ICrEAMTool isVW]) {
            [self showString:@"服务顾问至少选择两个连续的时间段!" forSeconds:1.5];
            return;
        }
        //还没有预约选择服务顾问时间----大众
        if (self.serverTimeModel.currentSelectedTimes.count == 0 && [ICrEAMTool isVW]) {
            [self showString:@"请先选择预约服务顾问及预约进站时间！" forSeconds:1.5];
            return;
        }
        
        //选择的时间要超过服务顾问结束时间----大众
        if (buttonIndex<self.serverTimeModel.lastServerIndex+1 && [ICrEAMTool isVW]) {
            [self showString:@"工位预约时间必须晚于服务顾问预约结束时间！" forSeconds:1.5];
            return;
        }
        
        //选择的时间要超过服务顾问开始时间----斯柯达
        if (buttonIndex<self.serverTimeModel.lastServerIndex-1 && ![ICrEAMTool isVW]) {
            [self showString:@"工位预约时间必须晚于服务顾问预约开始时间！" forSeconds:1.5];
            return;
        }
        //切换到其他工位
        if (self.selectedStationIndex && ![self.selectedStationIndex isEqualToString:[@(indexPath.row)stringValue]]) {
            ICMSelecteTimeModel *didSelecteTimeModel = [self.stationModels objectAtIndex:[self.selectedStationIndex integerValue]];
            [didSelecteTimeModel.currentSelectedTimes removeAllObjects];
        }
        selecteTimeModel = [self.stationModels objectAtIndex:indexPath.row];
        //选择的工位不能同时包含在线资源和非在线资源----大众
        BOOL haveOnline = [ICrEAMTool array:selecteTimeModel.currentSelectedTimes hasItemInOtherArray:selecteTimeModel.onlineSourceTimes];
        BOOL inOnline = [selecteTimeModel.onlineSourceTimes containsObject:[@(buttonIndex)stringValue]];
        if (selecteTimeModel.currentSelectedTimes.count&&((haveOnline&&!inOnline)||(!haveOnline&&inOnline))) {
            [self showString:@"工位预约时间不能同时包含在线资源和非在线资源！" forSeconds:1.5];
            return;
        }
        
        
        self.stationCode = selecteTimeModel.stationCode;
        
        self.selectedStationIndex = [@(indexPath.row)stringValue];
    }
    if (selecteTimeModel.currentSelectedTimes.count == 7 && ![selecteTimeModel.currentSelectedTimes containsObject:[@(buttonIndex)stringValue]]) {
        [self showString:@"工位最多能够选择七个时间格,请取消后再选择!" forSeconds:1.5];
        return;
    }
    [selecteTimeModel didSelectedTimeButtonIndex:buttonIndex];
    if (selecteTimeModel.currentSelectedTimes.count == 0) {
        if (!([ICrEAMTool isVW] && self.isOnline)) {
            self.selectedStationIndex = nil;
        }
    }
    dispatch_main_async_safe(^{
        [tableView reloadData];
    });
}

/*UIScrollViewDelegate*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.stationTableView) {
        self.stationTitleTableView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
    }
}

/*ICMDatePickerViewDelegate*/
#pragma mark    日历事件
- (void)calendarView:(PACACalendarView *)calendarView didSelectedDate:(NSDate *)selectedDate{
    self.selectedDate = selectedDate;
    NSString *dateString = [selectedDate separatorStyleDateTimeString];

    self.stepInTimeView.contentTextFeild.text = dateString;
    
    
    //获得可预约时间列表
    [self getTimeDataWithDate:dateString andUserId:self.userId];
}


#pragma mark    清空时间
- (void)delTime:(PACACalendarView *)calendarView{
    self.selectedDate = nil;
    self.stepInTimeView.contentTextFeild.text = @"";
}

/*ICMSelecteItemDataViewDelegate*/
#pragma mark    选择服务顾问
- (void)didSelectedItemTitle:(NSString *)itemTitle{
    NSString *serverCode = [[self.allServerNameAndCodes allKeysForObject:itemTitle]firstObject];
    self.serviceAdvisorView.contentText = itemTitle;
    [_itemDataView removeFromSuperview];
    self.userId = serverCode;
    [self getTimeDataWithDate:self.stepInTimeView.contentText andUserId:serverCode];
}

#pragma mark    获取服务顾问可预约时间
- (void)getTimeDataWithDate:(NSString *)date andUserId:(NSString *)userId
{
    if([self.delegate respondsToSelector:@selector(getTimeDataWithDate:andUserId:)])
    {
        [self.delegate getTimeDataWithDate:date andUserId:userId];
    }
    if ([ICrEAMTool isVW]) {
        [self getAllStationTimeDataWithDate:date];
    }
}

//请求数据
#pragma mark    获取服务顾问可预约时间
- (void)getTimeDataWithData:(id)data WithDate:(NSString *)date
{
    if (data) {
        NSLog(@"服务顾问可预约时间请求成功！");
        [self.serverTimeModel.haveSelectedTimes removeAllObjects];
        [self.serverTimeModel.currentSelectedTimes removeAllObjects];
        if ([ICrEAMTool isVW]) {
            if (![data[@"TT_BOOKING_ORDER"] isKindOfClass:[NSString class]]){
                NSArray *timeItems = data[@"TT_BOOKING_ORDER"];
                for (NSDictionary *timeItem in timeItems) {
                    NSString *timeLong = timeItem[@"RECEPTION_TIME"];
                    NSInteger count = [timeLong integerValue]/15;
                    NSString *comeTime;
                    if ([timeItem[@"BOOKING_COME_TIME"] isKindOfClass:[NSString class]]) {
                        comeTime = timeItem[@"BOOKING_COME_TIME"];
                    }else if ([timeItem[@"BOOKING_COME_TIME"] isKindOfClass:[NSNumber class]]){
                        comeTime = [timeItem[@"BOOKING_COME_TIME"] stringValue];
                    }else{
                        comeTime = [@((long)timeItem[@"BOOKING_COME_TIME"]) stringValue];
                    }
                    NSString *comingTime = [ICrEAMTool getDateHourMinuteWithTimeInterval:comeTime];
                    NSInteger startCount = [self hourAndMinTextGetCount:comingTime];
                    if (count>0) {
                        NSMutableArray *tempArray = [NSMutableArray array];
                        for (NSInteger i=0;i<count;i++) {
                            [tempArray addObject:[@(startCount+i)stringValue]];
                        }
                        [self.serverTimeModel.haveSelectedTimes addObjectsFromArray:tempArray];
                    }
                }
                [self.serverTimeModel.haveSelectedTimes removeObjectsInArray:self.currentSelectedTimes];
            }
        }else{
            if ([data[@"TT_BOOKING_RES"] isKindOfClass:[NSArray class]] && ((NSArray*)data[@"TT_BOOKING_RES"]).count) {
                for (NSDictionary *dateDic in data[@"TT_BOOKING_RES"]) {
                    NSString *appointmentTime = dateDic[@"BOOKING_DATE"];
                    appointmentTime = [[appointmentTime substringToIndex:appointmentTime.length-3]componentsSeparatedByString:@" "].lastObject;
                    NSInteger count = [self hourAndMinTextGetCount:appointmentTime];
                    if (![self.serverTimeModel.haveSelectedTimes containsObject:[@(count) stringValue]]&&count<=51&&count>=0) {
                        [self.serverTimeModel.haveSelectedTimes addObject:[@(count) stringValue]];
                        [self.serverTimeModel.haveSelectedTimes addObject:[@(count+1) stringValue]];
                    }
                }
            }
            [self.serverTimeModel.haveSelectedTimes removeObjectsInArray:self.currentSelectedTimes];
            self.SKServerEmptyTime = [data[@"PARAM_CODE"] floatValue];
        }
        if (self.currentSelectedTimes.count) {
            [self.serverTimeModel.currentSelectedTimes addObjectsFromArray:self.currentSelectedTimes];
            [self.currentSelectedTimes removeAllObjects];
        }
        dispatch_main_async_safe(^{
            [self markPassOverOfToday];
            [self.stepInTimeTableView reloadData];
        });
    }else{
        [self showString:@"服务顾问可预约时间请求失败！" forSeconds:1.5];
    }
    if (![ICrEAMTool isVW]) {
        [self getAllStationTimeDataWithDate:date];
    }
    
}

#pragma mark    获得工位的可预约时间
- (void)getAllStationTimeDataWithDate:(NSString*)date
{
    if([self.delegate respondsToSelector:@selector(getAllStationTimeDataWithDate:)])
    {
        [self.delegate getAllStationTimeDataWithDate:date];
    }
}

#pragma mark    获得工位的可预约时间
- (void)getAllStationTimeDataWithData:(id)data{
    if (data) {
        NSLog(@"工位可预约时间请求成功！");
        NSArray *stationNameAndCodes = data[@"TM_REPAIR_POSITION_ALL"];
        NSArray *datas;
        if ([ICrEAMTool isVW]) {
            datas= data[@"TM_REPAIR_POSITION"];
        }
        [self.stationModels removeAllObjects];
        self.selectedStationIndex = nil;
        for (NSDictionary *dataDic in stationNameAndCodes) {
            ICMSelecteTimeModel *timeModelAll = [[ICMSelecteTimeModel alloc]init];
            timeModelAll.stationCode = dataDic[@"LABOUR_POSITION_CODE"];
            timeModelAll.itemTitle = dataDic[@"LABOUR_POSITION_NAME"];
            
            if ([ICrEAMTool isVW]&&[datas isKindOfClass:[NSArray class]]){
                for (NSDictionary *dataDic in datas) {
                    ICMSelecteTimeModel *timeModel = [ICMSelecteTimeModel createSelecteTimeModelWithDataDic:dataDic];
                    timeModel.itemTitle = dataDic[@"LABOUR_POSITION_NAME"];
                    timeModel.stationCode = dataDic[@"LABOUR_POSITION_CODE"];
                    if ([timeModel.stationCode isEqualToString:timeModelAll.stationCode]) {
                        if (timeModel.haveSelectedTimes.count) {
                            [timeModelAll.haveSelectedTimes addObjectsFromArray:timeModel.haveSelectedTimes];
                        }
                        if (timeModel.currentSelectedTimes.count) {
                            [timeModelAll.currentSelectedTimes addObjectsFromArray:timeModel.currentSelectedTimes];
                        }
                        if (timeModel.onlineSourceTimes.count) {
                            [timeModelAll.onlineSourceTimes addObjectsFromArray:timeModel.onlineSourceTimes];
                        }
                    }
                }
                [self.stationModels addObject:timeModelAll];
            }else{
                [self.stationModels addObject:timeModelAll];
            }
        }
        
        [self addCurrentSelectedStation];
        
        dispatch_main_async_safe(^{
            [self markPassOverOfToday];
            [self.stationTitleTableView reloadData];
            [self.stationTableView reloadData];
        });
    }else{
        [self showString:@"工位可预约时间请求失败！" forSeconds:1.5];
    }
}

#pragma mark    获得所有的服务顾问姓名和编码
- (void)getAllServerNameAndCode
{
    if([self.delegate respondsToSelector:@selector(getAllServerNameAndCode)])
    {
        [self.delegate getAllServerNameAndCode];
    }
}

#pragma mark    获得所有的服务顾问姓名和编码
- (void)getAllServerNameAndCodeWithData:(id)data{
    if (data) {
        NSArray *allServers = data[@"TM_USER"];
        if ([allServers isKindOfClass:[NSArray class]]) {
            for (NSDictionary *server in allServers) {
                [self.allServerNameAndCodes setObject:server[@"EMPLOYEE_NAME"] forKey:server[@"EMPLOYEE_NO"]];
            }
            self.serviceAdvisorView.clickDataArray = [self.allServerNameAndCodes.allValues mutableCopy];
            self.serviceAdvisorView.contentText = self.allServerNameAndCodes[self.userId];
        }
    }
}

- (NSMutableDictionary *)allServerNameAndCodes{
    if (!_allServerNameAndCodes) {
        _allServerNameAndCodes = [NSMutableDictionary dictionary];
    }
    return _allServerNameAndCodes;
}

- (NSString *)selectedStationCode{
    _selectedStationCode = @"";
    if (self.selectedStationIndex) {
        ICMSelecteTimeModel *model = self.stationModels[[self.selectedStationIndex integerValue]];
        _selectedStationCode = model.stationCode;
    }
    return _selectedStationCode;
}

- (NSString *)selectedStationTitle{
    _selectedStationTitle = @"";
    if (self.selectedStationIndex) {
        ICMSelecteTimeModel *model = self.stationModels[[self.selectedStationIndex integerValue]];
        _selectedStationTitle = model.itemTitle;
    }
    return _selectedStationTitle;
}

- (NSString *)workingHour{
    _workingHour = @"";
    if (self.selectedStationIndex) {
        ICMSelecteTimeModel *model = self.stationModels[[self.selectedStationIndex integerValue]];
        float hour = model.currentSelectedTimes.count*0.25;
        _workingHour = hour != 0.0f?[@(hour) stringValue]:@"";
    }
    return _workingHour;
}

- (NSString *)stationCode{
    _stationCode = @"";
    if (self.selectedStationIndex) {
        ICMSelecteTimeModel *model = self.stationModels[[self.selectedStationIndex integerValue]];
        _stationCode = model.stationCode;
    }
    return _stationCode;
}

- (NSString *)RECEPTION_TIME{
    //float hour = self.serverTimeModel.haveSelectedTimes.count*0.25;
    if (!self.serverTimeModel.currentSelectedTimes.count) {
        return @"empty";
    }
    float hour = self.serverTimeModel.currentSelectedTimes.count*0.25;
    return [@(hour) stringValue];
}

- (NSString *)EST_STATION_TIME{
    if (!self.stationModels.count) {
        return @"empty";
    }
    if (!self.selectedStationIndex) {
        return @"empty";
    }
    ICMSelecteTimeModel *model = self.stationModels[[self.selectedStationIndex integerValue]];
    if (!model.currentSelectedTimes.count) {
        return @"empty";
    }
    NSInteger minCount = 100;
    for (NSString *index in model.currentSelectedTimes) {
        minCount = [index integerValue]<minCount?[index integerValue]:minCount;
    }
    if (minCount == 100) {
        minCount = 0;
    }
    NSInteger hour = minCount/4+7;
    NSInteger min =  minCount%4*15;
    NSString *beginTime = [NSString stringWithFormat:@"%@ %02ld:%02ld",self.stepInTimeView.contentText,hour,min];
    return beginTime;
}

#pragma mark    最小时间格序号
- (NSInteger)currentMinIndex{
    NSString *currentDateDesc = [ICrEAMTool getNowDateAndHour_Min];
    NSString *currentHour_Min = [[currentDateDesc componentsSeparatedByString:@" "]lastObject];
    
    NSInteger currentCount = [self hourAndMinTextGetCount:currentHour_Min];
    if (![ICrEAMTool isVW]){
        NSInteger addCount = self.SKServerEmptyTime*60/15;
        if ([self.stepInTimeView.contentText isEqualToString:[ICrEAMTool getNowDate]]){
            currentCount += addCount;
        }else{
            currentCount = 0;
            double emptyTime = [NSDate dateWithTimeIntervalSinceNow:self.SKServerEmptyTime*60*60].timeIntervalSince1970;
            NSArray *sevenArray = [self.stepInTimeView.contentText componentsSeparatedByString:@"-"];
            NSString *sevenDes = [NSString stringWithFormat:@"%@-%@-%@ 07:00",sevenArray[2],sevenArray[1],sevenArray[0]];
            double selectedDateSevenTime = [ICrEAMTool getDateWithDateDesc:sevenDes].timeIntervalSince1970;
            if (emptyTime>selectedDateSevenTime) {
                NSInteger emtpyCount = (emptyTime - selectedDateSevenTime)/(60*1000);
                currentCount = (emtpyCount>currentCount)?emtpyCount:currentCount;
            }
        }
    }
    if (currentCount < 1) {
        return -1;
    }else if (currentCount > 52){
        return 100;
    }else{
        return currentCount;
    }
}

- (NSInteger)hourAndMinTextGetCount:(NSString *)hourAndMin{
    if (hourAndMin.length>5) {
        hourAndMin = [hourAndMin substringToIndex:5];
    }
    NSString *currentHour = [[hourAndMin componentsSeparatedByString:@":"]firstObject];
    NSString *currentMin = [[hourAndMin componentsSeparatedByString:@":"]lastObject];
    NSInteger currentCount = ([currentHour integerValue]-7)*4;
    currentCount += [currentMin integerValue]/15+1;
    if ([currentMin integerValue]%15 == 0) {
        currentCount --;
    }
    return currentCount;
}

- (void)addCurrentSelectedStation{
    if (self.stationBeginTime && ![self.stationBeginTime isEqualToString:@""]) {
        for (ICMSelecteTimeModel *timeModel in self.stationModels) {
            if ([timeModel.stationCode isEqualToString:_stationCode]) {
                NSInteger minCount = [self hourAndMinTextGetCount:[self.stationBeginTime componentsSeparatedByString:@" "].lastObject];
                NSInteger count = [self.stationTime floatValue]/0.25;
                self.selectedStationIndex = [@([self.stationModels indexOfObject:timeModel]) stringValue];
                for (NSInteger i=0; i<count; i++) {
                    [timeModel.currentSelectedTimes PACA_AddObject:[@(minCount+i) stringValue]];
                    int deleteCount = 0;
                    while (deleteCount < 5) {
                        if ([timeModel.haveSelectedTimes containsObject:[@(minCount+i) stringValue]]) {
                            [timeModel.haveSelectedTimes removeObject:[@(minCount+i) stringValue]];
                        }
                        deleteCount ++;
                    }
                }
            }
        }
        self.stationBeginTime = nil;
    }
}

//判断品牌而返回当前显示日期
-(NSString *)dateStr{
    
    NSString *dateStr = [NSString string];
    
    if(![ICrEAMTool isVW]){
        dateStr = [ICrEAMTool dateToString:[ICrEAMTool tomorrowDate]];
        
    }else{
        
        dateStr = [ICrEAMTool getNowDate];
    }


    return dateStr;
}

@end









